package com.mycompany.server;

import com.mycompany.protocol.IntroduceCommand;
import com.mycompany.protocol.OkCommand;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import org.apache.log4j.Logger;

/**
 *
 * @author artyukhov
 */
public class Session implements Runnable {

    private final Socket clientSocket;
    private final ObjectOutputStream out;
    private final ObjectInputStream objectInputStream;
    private Container container;
    private String userName;

    public Session(Socket socket) {
        this.clientSocket = socket;
        try {
            objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
            out = new ObjectOutputStream(clientSocket.getOutputStream());
        } catch (IOException ex) {
            throw new IllegalStateException("cannot open output stream", ex);
        }
    }

    public void acceptName() throws IOException, ClassNotFoundException {
        IntroduceCommand introduceCommand = (IntroduceCommand) objectInputStream.readObject();
        userName = introduceCommand.getName();        
        System.out.println("introducing successfull: " + userName);
    }

    public String getUserName() {
        return userName;
    }

    public Container getContainer() {
        return container;
    }

    public void setContainer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Object inputObject = null;
                synchronized (objectInputStream) {
                    try {
                        inputObject = objectInputStream.readObject();
                    } catch (ClassNotFoundException ex) {
                        ex.printStackTrace();
                    }
                }
                if (inputObject == null) {
                    break;
                }
                Logger.getLogger(this.getClass()).info("recieving command");
            }
        } catch (IOException ioexc) {
            ioexc.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
